package eu.webmedia.recruitment.comics.strips;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;

@Component
public class CyanideAndHappinessStripUrlFinder {
	
	public String findUrl() {
		String pageContent;
		
		try {
			URL url = new URL("http://www.explosm.net/comics/new");
			InputStream stream = url.openStream();
			
			pageContent = getPageContent(stream);
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		Pattern descriptionPattern = Pattern.compile(".*src=\"(http://www.explosm.net/db/files/Comics/[^\"]*)\".*", Pattern.DOTALL);
		Matcher matcher = descriptionPattern.matcher(pageContent);
		
		if (!matcher.matches()) {
			return null;
		}
		
		return matcher.group(1);
	}

	
	private String getPageContent(InputStream stream) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		StringBuilder stringBuilder = new StringBuilder();
		
		String line;
		while ((line = reader.readLine()) != null) {
			stringBuilder.append(line);
		}
		reader.close();
		
		return stringBuilder.toString();
	}

}
